package servicios.biziGasteizRestaurantAdmin;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.ListIterator;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;

import connection.BDConnection;
import connection.Geocoding;

/**
 * Servlet implementation class loginValidator
 */
public class RestaurantAdminServices extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private BDConnection bdCon;
    private String CONTENT_TYPE = "text/json";
    private Geocoding geocode;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RestaurantAdminServices() {
    	super();
    	this.geocode = new Geocoding();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			processRequest(request, response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			response.getWriter().print("{\"success\":false, \"data\": \""+e.getMessage()+"\"}");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		try {
			processRequest(request, response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			this.bdCon.closeConnection();
			response.getWriter().print("{\"success\":false, \"data\": \""+e.getMessage()+"\"}");
		}
	}
	
	private void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String requestType = (String)request.getParameter("request");
		try{
			if(requestType.compareToIgnoreCase("GETRESTAURANT") == 0){
				this.getRestaurant(request, response);
			}
			else if(requestType.compareToIgnoreCase("UPDATEMAINRESTAURANT") == 0){
				this.updateMainRestaurant(request, response);
			}
			else if(requestType.compareToIgnoreCase("GETGALLERY") == 0){
				this.getGalleryPhotos(request, response);
			}
			else if(requestType.compareToIgnoreCase("GETMAINPHOTO") == 0){
				this.getMainPhoto(request, response);
			}
			else if(requestType.compareToIgnoreCase("ADDPHOTO") == 0){
				this.addPhoto(request, response);
			}
			else if(requestType.compareToIgnoreCase("DELETEPHOTO") == 0){
				this.deletePhoto(request, response);
			}
			else if(requestType.compareToIgnoreCase("ADDMAINPHOTO") == 0){
				this.addMainPhoto(request, response);
			}
			else if(requestType.compareToIgnoreCase("UPDATEMAINPHOTOURL") == 0){
				this.updateMainPhotoUrl(request, response);
			}
			else if(requestType.compareToIgnoreCase("GETMENUS") == 0){
				this.getMenus(request, response);
			}
			else if(requestType.compareToIgnoreCase("UPDATEMENU") == 0){
				this.updateMenu(request, response);
			}
			else if(requestType.compareToIgnoreCase("NEWMENU") == 0){
				this.newMenu(request, response);
			}
			else if(requestType.compareToIgnoreCase("DELETEMENU") == 0){
				this.deleteMenu(request, response);
			}
		}
		catch(Exception oo){oo.printStackTrace();}
	}
	
	private void newMenu(HttpServletRequest request, HttpServletResponse  response) throws ClassNotFoundException, IOException{
		BDConnection bdCon = new BDConnection();
		String values = "";
		String columns= "";
		String sqlQuery = "";
		try{
			List items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
			ListIterator iterator = items.listIterator();
	        while (iterator.hasNext()) {
	        	FileItem item = (FileItem) iterator.next();
	        	 if (item.isFormField()) {
	        		 String fieldname = item.getFieldName();
		             String fieldvalue = item.getString();
		             if(fieldname.equals("precio")){
		            	 values = values + fieldvalue +",";
		            	 columns = columns + fieldname +",";
		             }
		             else if(fieldname.equals("restauranteid")){
		            	 values = values + fieldvalue +",";
		            	 columns = columns + fieldname +",";
		             }
		             else if(fieldname.equals("menuid")){
		             }
		             else{
		            	 values = values + "'"+fieldvalue +"',";
		            	 columns = columns + fieldname +",";
	                }
	        	 }
	        	 else {
	                String fieldname = item.getFieldName();
	                String filename = item.getName();
	                if(!filename.equals("")){
		                InputStream filecontent = item.getInputStream();
		                values = values + "'./images/eventos/restaurantes/"+filename+"',";
		                columns = columns + fieldname+",";
		                String relativePath = request.getSession().getServletContext().getRealPath("/images/eventos/restaurantes");
		                File f=new File(relativePath+File.separator+filename);//Aqui le dan el nombre y/o con la ruta del archivo salida
		                OutputStream os=new FileOutputStream(f);
		                byte[] buf =new byte[1024];//Actualizado me olvide del 1024
		                int len;
		                while((len=filecontent.read(buf))>0){
		                	os.write(buf,0,len);
		                }
		                os.close();
		                filecontent.close();
	                }
	            }
	        }
	        values = values.substring(0,values.length() -1);
        	columns = columns.substring(0, columns.length() -1);
        	sqlQuery = "INSERT INTO menu ("+columns+") VALUES ("+values+")";
        	System.out.println(sqlQuery);
        	JSONObject resJson = new JSONObject();
	        int rs = bdCon.executeUpdate(sqlQuery);
	        if(rs > 0){
				resJson.put("success", true);
			}
			else{
				resJson.put("success", false);
			}
			response.getWriter().write(resJson.toString());
			bdCon.closeConnection();
		}
		catch(Exception e){
			e.printStackTrace();
			response.getWriter().print("{\"success\":false, \"data\": \""+e.getMessage()+"\"}");
			bdCon.closeConnection();
		}
	}
	
	private void updateMenu(HttpServletRequest request, HttpServletResponse  response) throws ClassNotFoundException, IOException{
		BDConnection bdCon = new BDConnection();
		String updates = "";
		String sqlQuery = "";
		String restauranteid = "";
		String menuid = "";
		try{
			List items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
			ListIterator iterator = items.listIterator();
	        while (iterator.hasNext()) {
	        	FileItem item = (FileItem) iterator.next();
	        	 if (item.isFormField()) {
	        		 String fieldname = item.getFieldName();
		             String fieldvalue = item.getString();
		             if(fieldname.equals("precio")){
		            	 updates = updates+" "+fieldname+"="+fieldvalue+",";
		             }
		             else if(fieldname.equals("restauranteid")){
		            	 restauranteid = fieldvalue;
		             }
		             else if(fieldname.equals("menuid")){
		            	 menuid = fieldvalue;
		             }
		             else{
		            	 updates = updates+" "+fieldname+"='"+fieldvalue+"',";
	                }
	        	 }
	        	 else {
	                String fieldname = item.getFieldName();
	                String filename = item.getName();
	                if(!filename.equals("")){
		                InputStream filecontent = item.getInputStream();
		                updates = updates+" "+fieldname+"='./images/eventos/restaurantes/"+filename+"',";
		                String relativePath = request.getSession().getServletContext().getRealPath("/images/eventos/restaurantes");
		                File f=new File(relativePath+File.separator+filename);//Aqui le dan el nombre y/o con la ruta del archivo salida
		                OutputStream os=new FileOutputStream(f);
		                byte[] buf =new byte[1024];//Actualizado me olvide del 1024
		                int len;
		                while((len=filecontent.read(buf))>0){
		                	os.write(buf,0,len);
		                }
		                os.close();
		                filecontent.close();
	                }
	            }
	        }
	        updates = updates.substring(0, updates.length()-1);
        	sqlQuery = "UPDATE  menu SET "+updates+" where restauranteid="+restauranteid+" and menuid="+menuid;
        	System.out.println(sqlQuery);
        	JSONObject resJson = new JSONObject();
	        int rs = bdCon.executeUpdate(sqlQuery);
	        if(rs > 0){
				resJson.put("success", true);
			}
			else{
				resJson.put("success", false);
			}
			response.getWriter().write(resJson.toString());
			bdCon.closeConnection();
		}
		catch(Exception e){
			e.printStackTrace();
			response.getWriter().print("{\"success\":false, \"data\": \""+e.getMessage()+"\"}");
			bdCon.closeConnection();
		}
	}
	
	private void deleteMenu(HttpServletRequest request, HttpServletResponse  response) throws SQLException, IOException, ClassNotFoundException{
		BDConnection bdCon = new BDConnection();
		String menuid = request.getParameter("menuid");
		String deleteRestaurantSql = "DELETE FROM menu WHERE menuid='"+menuid+"'";
		JSONObject res = new JSONObject();
		try{
			int rows = bdCon.executeUpdate(deleteRestaurantSql);
			if(rows > 0){
				res.put("success", true);
			}
			else{
				res.put("success", false);
			}
			bdCon.closeConnection();
			
			response.getWriter().print(res);
		}
		catch(Exception e){
			e.printStackTrace();
			response.getWriter().print("{\"success\":false, \"data\": \""+e.getMessage()+"\"}");
			bdCon.closeConnection();
		}
	}
	
	
	
	
	private void getMenus(HttpServletRequest request, HttpServletResponse response) throws JSONException, IOException, ClassNotFoundException{
		BDConnection bdCon = new BDConnection();
		try{
			response.setContentType(this.CONTENT_TYPE);
			PrintWriter print = response.getWriter();
			
			String id = request.getParameter("restauranteid");
			String type = request.getParameter("type");
			String subType = request.getParameter("subType");
			String sql = "";
			if(subType != null){
				sql = "SELECT * FROM menu WHERE tipo='"+type+"'AND sub_tipo='"+subType+"' AND restauranteid="+id;
			}else{
				sql = "SELECT * FROM menu WHERE tipo='"+type+"' AND restauranteid="+id;
			}
			System.out.println(sql);
			ResultSet rs = bdCon.executeQuery(sql);
			JSONArray menusArray = new JSONArray();
			while(rs.next()){
				JSONObject menuItem = new JSONObject();
				menuItem.put("precio", rs.getDouble("precio"));
				menuItem.put("descripcion", rs.getString("descripcion"));
				menuItem.put("menuid", rs.getInt("menuid"));
				menuItem.put("foto", rs.getString("foto"));
				menuItem.put("text", rs.getString("nombre"));
				menuItem.put("tipo", rs.getString("tipo"));
				menuItem.put("restauranteid", rs.getInt("restauranteid"));
				menuItem.put("leaf", true);
				if(rs.getString("tipo").equals("Cena")){
					menuItem.put("icon", "./images/icons/menu-dinner.png");
				}
				else if(rs.getString("tipo").equals("Oferta")){
					menuItem.put("icon", "./images/icons/star-icon.png");
				}
				else if(rs.getString("tipo").equals("Desayuno")){
					menuItem.put("icon", "./images/icons/breakfast.gif");
				}
				else if(rs.getString("tipo").equals("Pintxo")){
					menuItem.put("icon", "./images/icons/bocata.png");
				}
				else{
					menuItem.put("icon", "./images/icons/food_menu.png");
				}
				
				menusArray.put(menuItem);
			}
			print.print(menusArray.toString());
		}
		catch(Exception oo){
			JSONObject res = new JSONObject();
			res.put("success", false);
			res.put("data",oo.getMessage());
			oo.printStackTrace();
			bdCon.closeConnection();
			response.getWriter().write(res.toString());		
		}
	}
	
	private void updateMainPhotoUrl(HttpServletRequest request, HttpServletResponse response) throws JSONException, IOException, ClassNotFoundException{
		BDConnection bdCon = new BDConnection();
		try{
			response.setContentType(this.CONTENT_TYPE);
			PrintWriter print = response.getWriter();
			
			String id = request.getParameter("id");
			String url = request.getParameter("url");
			JSONObject resJson = new JSONObject();
	
			int rs1 = bdCon.executeUpdate("UPDATE restaurantes SET foto_principal ='"+url+"' WHERE restaurantid="+id);
			if(rs1 > 0){
				resJson.put("success", true);
			}
			else{
				resJson.put("success", false);
			}
			print.print(resJson.toString());
		}
		catch(Exception oo){
			JSONObject res = new JSONObject();
			res.put("success", false);
			res.put("data",oo.getMessage());
			oo.printStackTrace();
			bdCon.closeConnection();
			response.getWriter().write(res.toString());		
		}
	}
	
	private void addMainPhoto(HttpServletRequest request, HttpServletResponse response) throws IOException, ClassNotFoundException{

		String sqlQuery = "";
		String id = request.getParameter("id");
		String nombre = request.getParameter("name");
		BDConnection bdCon = new BDConnection();
		try{
			List items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
			ListIterator iterator = items.listIterator();
	        while (iterator.hasNext()) {
	        	FileItem item = (FileItem) iterator.next();
	            if (!item.isFormField()) {
	                InputStream filecontent = item.getInputStream();
	                String relativePath = request.getSession().getServletContext().getRealPath("/images/eventos/restaurantes");
	                File f=new File(relativePath+File.separator+nombre);//Aqui le dan el nombre y/o con la ruta del archivo salida
	                OutputStream os=new FileOutputStream(f);
	                byte[] buf =new byte[1024];//Actualizado me olvide del 1024
	                int len;
	                while((len=filecontent.read(buf))>0){
	                	os.write(buf,0,len);
	                }
	                os.close();
	                filecontent.close();
	            }
	        }
        	sqlQuery = "UPDATE restaurantes SET foto_principal ='./images/eventos/restaurantes/"+nombre+"' WHERE restaurantid="+id;
        	JSONObject resJson = new JSONObject();
	        int rs = bdCon.executeUpdate(sqlQuery);
	        if(rs > 0){
				resJson.put("success", true);
			}
			else{
				resJson.put("success", false);
			}
			response.getWriter().write(resJson.toString());
			bdCon.closeConnection();
	        
		}catch(Exception o){
			o.printStackTrace();
			response.getWriter().print("{\"success\":false, \"data\": \""+o.getMessage()+"\"}");
			bdCon.closeConnection();
		}
	}
	
	
	private void deletePhoto(HttpServletRequest request, HttpServletResponse response) throws IOException, ClassNotFoundException{
		response.setContentType(this.CONTENT_TYPE);
		
		String id = request.getParameter("id");
		String url = request.getParameter("url");
		BDConnection bdCon = new BDConnection();
		try{
			String sql = "DELETE FROM restaurantes_fotos where restauranteid="+id+" AND url='"+url+"'";
			int rs = bdCon.executeUpdate(sql);
			JSONObject resJson = new JSONObject();
			if(rs>0){
				resJson.put("success", true);
			}
			else{
				resJson.put("success", false);
			}
			
			String relativePath = request.getSession().getServletContext().getRealPath("/images/eventos/restaurantes");
			String nombre = url.substring(url.lastIndexOf('/')+1);
            File f=new File(relativePath+File.separator+nombre);//Aqui le dan el nombre y/o con la ruta del archivo salida
            if(f.exists()){
            	f.delete();
            }
			response.getWriter().write(resJson.toString());
			bdCon.closeConnection();
	        
		}catch(Exception o){
			o.printStackTrace();
			response.getWriter().print("{\"success\":false, \"data\": \""+o.getMessage()+"\"}");
			bdCon.closeConnection();
		}
	}
	
	private void addPhoto(HttpServletRequest request, HttpServletResponse response) throws IOException, ClassNotFoundException{

		String sqlQuery = "";
		String id = request.getParameter("id");
		String nombre = request.getParameter("name");
		BDConnection bdCon = new BDConnection();
		try{
			List items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
			ListIterator iterator = items.listIterator();
	        while (iterator.hasNext()) {
	        	FileItem item = (FileItem) iterator.next();
	            if (!item.isFormField()) {
	                InputStream filecontent = item.getInputStream();
	                String relativePath = request.getSession().getServletContext().getRealPath("/images/eventos/restaurantes");
	                File f=new File(relativePath+File.separator+nombre);//Aqui le dan el nombre y/o con la ruta del archivo salida
	                OutputStream os=new FileOutputStream(f);
	                byte[] buf =new byte[1024];//Actualizado me olvide del 1024
	                int len;
	                while((len=filecontent.read(buf))>0){
	                	os.write(buf,0,len);
	                }
	                os.close();
	                filecontent.close();
	            }
	        }
        	sqlQuery = "INSERT INTO restaurantes_fotos (restauranteid,url) VALUES ("+id+",'./images/eventos/restaurantes/"+nombre+"')";
        	JSONObject resJson = new JSONObject();
	        int rs = bdCon.executeUpdate(sqlQuery);
	        if(rs > 0){
				resJson.put("success", true);
			}
			else{
				resJson.put("success", false);
			}
			response.getWriter().write(resJson.toString());
			bdCon.closeConnection();
	        
		}catch(Exception o){
			o.printStackTrace();
			response.getWriter().print("{\"success\":false, \"data\": \""+o.getMessage()+"\"}");
			bdCon.closeConnection();
		}
	}
	
	private void getGalleryPhotos(HttpServletRequest request, HttpServletResponse response) throws JSONException, IOException, ClassNotFoundException{
		BDConnection bdCon = new BDConnection();
		try{
			response.setContentType(this.CONTENT_TYPE);
			PrintWriter print = response.getWriter();
			
			String id = request.getParameter("id");
			
			JSONObject resJson = new JSONObject();
			JSONArray resArray = new JSONArray();
	
			ResultSet rs1 = bdCon.executeQuery("SELECT * FROM restaurantes_fotos WHERE restauranteid='"+id+"'");
			while(rs1.next()){
				
				JSONObject fotoGallery = new JSONObject();
				String foto = rs1.getString("url");
				fotoGallery.put("name", foto.substring(foto.lastIndexOf('/')+1, foto.length()));
				fotoGallery.put("url", foto);
				
				resArray.put(fotoGallery);
			}
			
			resJson.put("gallery", resArray);
			
			print.print(resJson.toString());
		}
		catch(Exception oo){
			JSONObject res = new JSONObject();
			res.put("success", false);
			res.put("data",oo.getMessage());
			oo.printStackTrace();
			bdCon.closeConnection();
			response.getWriter().write(res.toString());		
		}
	}
	
	private void getMainPhoto(HttpServletRequest request, HttpServletResponse response) throws JSONException, IOException, ClassNotFoundException{
		BDConnection bdCon = new BDConnection();
		try{
			response.setContentType(this.CONTENT_TYPE);
			PrintWriter print = response.getWriter();
			
			String id = request.getParameter("id");
			
			String sql = "SELECT foto_principal,descripcion_corta FROM restaurantes WHERE restaurantid="+id;
			ResultSet rs = bdCon.executeQuery(sql);
			JSONObject resJson = new JSONObject();
			JSONObject fotoPrinItem = new JSONObject();
			rs.next();
			
			String foto_principal = rs.getString("foto_principal");
			String descripcion_corta = rs.getString("descripcion_corta");
			fotoPrinItem.put("name", foto_principal.substring(foto_principal.lastIndexOf('/'), foto_principal.length()));
			fotoPrinItem.put("url", foto_principal);
			fotoPrinItem.put("descripcion_corta", descripcion_corta);

			resJson.put("success", true);
			resJson.put("mainPhoto", fotoPrinItem);
			print.print(resJson.toString());
		}
		catch(Exception oo){
			JSONObject res = new JSONObject();
			res.put("success", false);
			res.put("data",oo.getMessage());
			oo.printStackTrace();
			bdCon.closeConnection();
			response.getWriter().write(res.toString());		
		}
	}
	
	private void updateMainRestaurant(HttpServletRequest request, HttpServletResponse response) throws JSONException, IOException, ClassNotFoundException{
		BDConnection bdCon = new BDConnection();
		try{
			response.setContentType(this.CONTENT_TYPE);
			PrintWriter print = response.getWriter();
			
			String id = request.getParameter("id");
			String nombre= request.getParameter("nombre");
			String calle = request.getParameter("calle");
			String descripcion = request.getParameter("descripcion");
			String descripcion_corta = request.getParameter("descripcion_corta");
			String descripcion_normal = request.getParameter("descripcion_normal");
			String email = request.getParameter("email");
			String horario = request.getParameter("horario");
			String telefono = request.getParameter("telefono");
			String tipo_bar = request.getParameter("tipo_bar");
			
			String geocoded = this.geocode.geocodeStreet(calle);
			
			String sql = "UPDATE restaurantes SET nombre='"+nombre+"', calle='"+calle+"', descripcion='"+descripcion+"'," +
					"descripcion_normal='"+descripcion_normal+"', descripcion_corta='"+descripcion_corta+"', email='"+email+"'," +
					"horario='"+horario+"', telefono='"+telefono+"', tipo='"+tipo_bar+"', localizacion="+geocoded+" " +
					" WHERE restaurantid="+id;
			int rs = bdCon.executeUpdate(sql);
			JSONObject resJson = new JSONObject();
			if(rs > 0){
				resJson.put("success", true);
			}
			else{
				resJson.put("success", false);
			}
			bdCon.closeConnection();
			print.print(resJson.toString());
		}
		catch(Exception oo){
			JSONObject res = new JSONObject();
			res.put("success", false);
			res.put("data",oo.getMessage());
			oo.printStackTrace();
			bdCon.closeConnection();
			response.getWriter().write(res.toString());		
		}
	}
	
	private void getRestaurant(HttpServletRequest request, HttpServletResponse response) throws JSONException, IOException, ClassNotFoundException{
		BDConnection bdCon = new BDConnection();
		try{
			response.setContentType(this.CONTENT_TYPE);
			PrintWriter print = response.getWriter();
			
			String code = request.getParameter("code");
			
			String sqlStr = "SELECT nombre,descripcion_corta,tipo,foto_principal," +
					"ST_ASTEXT(localizacion) as localizacion,horario," +
					"restaurantid,descripcion,calle,descripcion_normal,telefono,email  FROM restaurantes where restaurantid="+code;
			ResultSet rs = bdCon.executeQuery(sqlStr);
			
			JSONObject itemJson = new JSONObject();

			if(rs.next()){
				
				itemJson.put("nombre", rs.getString("nombre"));
				itemJson.put("descripcion_corta", rs.getString("descripcion_corta"));
				itemJson.put("tipo", rs.getString("tipo"));
				itemJson.put("foto_principal", rs.getString("foto_principal"));
				itemJson.put("localizacion", rs.getString("localizacion"));
				itemJson.put("horario", rs.getString("horario"));
				itemJson.put("restaurantid", rs.getInt("restaurantid"));
				itemJson.put("descripcion", rs.getString("descripcion"));
				itemJson.put("calle", rs.getString("calle"));
				itemJson.put("descripcion_normal", rs.getString("descripcion_normal"));
				itemJson.put("telefono", rs.getString("telefono"));
				itemJson.put("email", rs.getString("email"));
				JSONArray menuJsonArray = new JSONArray();
				String sqlMenu = "SELECT * FROM MENU WHERE restauranteid='"+code+"'";
				ResultSet rs1 = bdCon.executeQuery(sqlMenu);
				while(rs1.next()){
					JSONObject menuJson = new JSONObject();
					menuJson.put("restauranteid", rs1.getString("restauranteid"));
					menuJson.put("precio", rs1.getDouble("precio"));
					menuJson.put("descripcion", rs1.getString("descripcion"));
					menuJson.put("menuid", rs1.getInt("menuid"));
					menuJson.put("foto", rs1.getString("foto"));
					menuJson.put("nombre", rs1.getString("nombre"));
					menuJson.put("tipo", rs1.getString("tipo"));
					menuJsonArray.put(menuJson);
				}
				itemJson.put("menus", menuJsonArray);
				ResultSet rs2 = bdCon.executeQuery("SELECT * FROM restaurantes_fotos WHERE restauranteid='"+code+"'");
				JSONArray fotosArray = new JSONArray();
				while(rs2.next()){
					fotosArray.put(rs2.getString("url"));
				}
				itemJson.put("images", fotosArray);
			}
			JSONObject resJson = new JSONObject();
			resJson.put("success", true);
			resJson.put("data", itemJson);
			
			print.write(resJson.toString());
			bdCon.closeConnection();
		}
		catch(Exception oo){
			JSONObject res = new JSONObject();
			res.put("success", false);
			res.put("data",oo.getMessage());
			oo.printStackTrace();
			bdCon.closeConnection();
			response.getWriter().write(res.toString());
			
		}
	}
}
